'use strict';

const Controller = require('egg').Controller;

class ToolsController extends Controller {

  async index() {
    const ctx = this.ctx;
    const page = ctx.request.query.page || 1;
    const res = await ctx.service.article.articlePageList({}, page);
    const lists = res.rows;
    const count = res.count;
    const html_page = await ctx.service.paginator.paginator(count, page);
    const typeList = ctx.service.article.geTypeList();
    const data_list = {
      lists,
      page: html_page,
      typeList,
    };
    await ctx.render(ctx.view_path(), data_list);
  }

  async add() {
    const ctx = this.ctx;
    const method = ctx.request.method;
    if (method === 'POST') {
      const postData = ctx.request.body
      let body = { status: 0 };
      let act = postData.act;
      let res = false;
      if (postData.title && postData.content && postData.type_id && !body.message) {
        switch (act) {
          case 'add':
            {
              res = ctx.service.article.setData(postData);
              break;
            }
          case 'edit':
            {
              const id = ctx.request.body.id || 0;
              if (id) {
                res = ctx.service.article.setData(postData, { id });
              }
              break;
            }
          default: break;
        }
      } else if (act === 'rmv') {
        const id = ctx.request.body.id || 0;
        if (id) res = await ctx.model.Article.destroy({ where: { id } });
      } else {
        if (!body.message) body.message = '标题、内容和文章类型必须必须';
      }
      if (res !== false) body = res ? { status: 1, message: '操作成功' } : { status: 0, message: '操作失败' };
      ctx.body = body;
      ctx.status = 200;
    } else {
      let act = 'add';
      const id = ctx.request.query.id || 0;
      let info = {};
      if (id) {
        info = await ctx.model.Article.findById(id, { raw: true });
        if (info) act = 'edit';
      }
      const typeList = ctx.service.article.geTypeList();
      const data_list = {
        act,
        info,
        typeList,
      };
      await ctx.render(ctx.view_path(), data_list);
    }
  }

}

module.exports = ToolsController;
